#include<stdio.h>
#include<stdbool.h>
#define len 200000
#define maxn 1005
typedef struct { int x, y; }P;
int maze[maxn][maxn], vis[maxn][maxn];
int m, n;
int ans;
int l=0, r=1000, mid;
const int dx[] = {0, 1, 0, -1};
const int dy[] = {1, 0, -1, 0};
P q[len];
int ql, qr;
void push(int x, int y) {
  P t={x, y};
  int qt = qr;
  qr = (qr+1)%len;
  q[qt]=t;
}
P pop() {
  int qt = ql;
  ql = (ql+1)%len;
  return q[qt];
}
bool empty() { return ql==qr; }
void clear() { ql=qr=0; }
bool bfs(int lmt) {
  for(int i=0; i<n; ++i)
    for(int j=0; j<m; ++j)
      vis[i][j] = (maze[i][j]>lmt);
  push(0, 0);
  while(!empty()) {
    P cur = pop();
    int x = cur.x, y = cur.y;
    vis[x][y] = true;
    for(int i=0; i<4; ++i) {
      int nx = x+dx[i];
      int ny = y+dy[i];
      if(nx<0 || ny<0 || nx>=n || ny>=m
          || vis[nx][ny])continue;
      if(nx==n-1) {
        clear();
        return true;
      }
      push(nx, ny);
    }
  }
  return false;
}
int main() {
#ifndef ONLINE_JUDGE
   freopen("in2.txt" , "r", stdin);
#endif
  scanf("%d%d", &n, &m);
  for(int i=0; i<n; ++i)
    for(int j=0; j<m; ++j)
      scanf("%d", &maze[i][j]);
  while(l<=r) {
    mid = (l+r)/2;
    if(bfs(mid)) ans = mid, r = mid-1;
    else l = mid+1;
  }
  printf("%d\n", ans);
}
